<?php

/**
 * This file is part of the Framework03 PHP framework.
 * @author Walter Tamboer
 * @package Framework03
 */

class FW_Database_Adapter_MySQLi_Rowset extends FW_Database_Adapter_Rowset
{
    /**
     * @var resource The handle of the result set.
     */
    private $handle;

    /**
     * @var int The amount of available rows.
     */
    private $count = 0;
    
    /**
     * @var int The current pointer for the iterator.
     */
    private $pointer = 0;
    
    /**
     * @var array An array with all the rows.
     */
    private $rows = array();

    /**
     * Initializes a new instance of this class.
     * @param FW_Database_Adapter $adapter
     * @param resource $handle
     */
    public function __construct(FW_Database_Adapter_Abstract $adapter, $handle)
    {
        parent::__construct($adapter);
        
        $this->handle = $handle;

        $this->count = mysqli_num_rows($handle);
    }

    /**
     * Seeks the given index in the row list.
     * @return mixed
     */
    public function seek($index)
    {
        $index = (int)$index;
        
        if ($index < 0 || $index > $this->count)
            throw new FW_Database_Adapter_Exception("Illegal index $index");

        $this->pointer = $index;
        return $this;
    }

    /**
     * Gets the current row from the result set.
     * @return mixed
     */
    public function current()
    {
        if (!isset($this->rows[$this->pointer]))
            $this->rows[$this->pointer] = $this->handle->fetch_object();

        return $this->rows[$this->pointer];
    }

    /**
     * Gets the next row from the result set.
     * @return mixed
     */
    public function next()
    {
        $this->pointer++;
    }

    /**
     * Gets the current key from the result set.
     * @return mixed
     */
    public function key()
    {
        return $this->pointer;
    }

    /**
     * Rewinds the iterator back to the beginning.
     * @return FW_Database_Adapter_MySQLi_Rowset
     */
    public function rewind()
    {
        $this->pointer = 0;
        return $this;
    }

    /**
     * Gets the amount of available rows.
     * @return int
     */
    public function count()
    {
        return $this->count;
    }

    /**
     * Checks if the current pointer is still valid.
     * @return bool
     */
    public function valid()
    {
        return $this->pointer < $this->count;
    }
}
